import {ErrorHandler, Injectable} from '@angular/core';
import {ApiPath} from "../config/api-path";
import {HttpHeaders, HttpParams} from "@angular/common/http";
import {HttpClient} from '@angular/common/http';
import {catchError, Observable, retry, throwError} from "rxjs";
import {ServerResponse} from "../model/server-response";
import {AuthService} from "./auth.service";

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(
    private http: HttpClient,
    private tokenService: AuthService,
  ) {
  }

  private static readonly SERVER_PATH = ApiPath.SERVER_PATH;
  private static readonly IMAGE_SERVER_PATH = ApiPath.IMAGE_SERVER_PATH;

  private options = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
    }),
  };

  public httpGet<T>(url: string, params?: {},): Observable<ServerResponse<T>> {
    let httpOptions = this.options;
    let requestUrl: string = "";
    if (params) {
      let paramStr = "";
      for (let key in params) {
        paramStr += key + "=" + params[key] + "&";
      }
      requestUrl = HttpService.SERVER_PATH + url + "?" + paramStr;
    } else {
      requestUrl = HttpService.SERVER_PATH + url;
    }
    console.debug("requestUrl",requestUrl)
    if (this.tokenService.getToken()) {
      httpOptions.headers = this.options.headers.set('token', this.tokenService.getToken());
    }
    const res = this.http.get<ServerResponse<T>>(requestUrl, httpOptions)
      .pipe(
        retry(3),
        catchError(error => {
          // console.debug(error);
          return throwError(error)
        })
      );
    let data: ServerResponse<T>;
    res.subscribe(res => {
      if (res.code === -1) {
        if (res.msg == "请登录") {
          this.tokenService.delToken()
        }
      }
      data = res;
    })
    return res;
  }

  public httpPost<T>(url: string, body: any,): Observable<ServerResponse<T>> {
    let httpOptions = this.options;
    if (this.tokenService.getToken()) {
      httpOptions.headers = this.options.headers.set('token', this.tokenService.getToken());
    }
    // console.debug("body", body)
    // console.debug(this.options)
    let res = this.http.post<ServerResponse<T>>(HttpService.SERVER_PATH + url, body, httpOptions).pipe(
      retry(3),
      catchError(error => {
        // console.debug(error);
        return throwError(error)
      })
    );
    let data: ServerResponse<T>;
    res.subscribe(r => {
      if (r.code === -1) {
        if (r.msg == "请登录") {
          this.tokenService.delToken()
        }
      }
      // console.debug(r)
      data = r;
    })
    // console.debug("data", data)
    return res;
  }

  public httpDel<T>(url: string, body: any,): Observable<ServerResponse<T>> {
    let res = this.http.post<ServerResponse<T>>(HttpService.SERVER_PATH + url, this.options).pipe(
      retry(3),
      catchError(error => {
        // console.debug(error);
        return throwError(error)
      })
    );
    let data: ServerResponse<T>;
    res.subscribe(res => {
      if (res.code === -1) {
        if (res.msg == "请登录") {
          this.tokenService.delToken()
        }
      }
      data = res;
    })
    return res;
  }

}
